﻿using Core.Users;
using Microsoft.AspNet.SignalR;
using Microsoft.Practices.ServiceLocation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Web;

namespace RhotCMS.Hubs
{
    public class Chat : Hub
    {
        ICurrentUserService _currentUserService;
        HubUserManager _hubUserManager;

        protected IIdentity User
        {
            get
            {
                return _hubUserManager.Get(Context.ConnectionId);
            }
        }

        public Chat()
        {
            _currentUserService = ServiceLocator.Current.GetInstance<ICurrentUserService>();
            _hubUserManager = new HubUserManager();   
        }

        public override Task OnConnected()
        {           
            _hubUserManager.Add(Context.ConnectionId, _currentUserService.CurrentUser.Identity);

            var userName = User.Name;

            Clients.All.updateUserList(_hubUserManager.GetAll().Select(x=>x.Name).Distinct());

            if (_hubUserManager.GetUserCountByName(userName) == 1)
            {
                return Clients.Others.userEvent(String.Format("{0} {1} connected", DateTime.Now.ToString("hh:mm:ss"), userName));   
            }
            else
            {
                return null;
            }                                 
        }

        public override Task OnDisconnected()
        {
            var userName = User.Name;

            _hubUserManager.Remove(Context.ConnectionId);

            Clients.All.updateUserList(_hubUserManager.GetAll().Select(x => x.Name).Distinct());

            if (_hubUserManager.GetUserCountByName(userName) == 0)
            {
                return Clients.Others.userEvent(String.Format("{0} {1} disconnected", DateTime.Now.ToString("hh:mm:ss"), userName));
            }
            else
            {
                return null;
            }
        }

        public override Task OnReconnected()
        {           
            _hubUserManager.Add(Context.ConnectionId, _currentUserService.CurrentUser.Identity);

            Clients.All.updateUserList(_hubUserManager.GetAll().Select(x => x.Name).Distinct());

            var userName = User.Name;

            return Clients.Others.userEventd(String.Format("{0} {1} reconnected", DateTime.Now.ToString("hh:mm:ss"),  userName));
        }

        public void Send(string message)
        {

            Clients.All.send(String.Format("{0} {1}: {2}", DateTime.Now.ToString("hh:mm:ss"), _currentUserService.CurrentUser.Identity.Name, message));
        }
    }
}